import React from 'react';
import {Table, Row, Col, Form, InputNumber, Button, Tabs, Input, message} from 'antd';
const FormItem = Form.Item;

const R = require('ramda');
const TabPane = Tabs.TabPane;

export default Form.create({wrappedComponentRef: true})(class CostList extends React.Component {
    constructor(props) {
        super(props);
        this.initData(props.dataSource, true);
    }

    componentWillReceiveProps(nextProps) {
        if (!R.equals(this.props.dataSource)(nextProps.dataSource)) {
            this.initData(nextProps.dataSource)
        }
    }

    initData = (dataSource, flag) => {
        dataSource = R.isNil(dataSource) ? {} : dataSource;
        let defaultFeeList = R.isNil(dataSource.feeList) ? [] : dataSource.feeList;
        if (flag) {
            this.state = {
                feeList: defaultFeeList,
                defaultFeeList: defaultFeeList,
                tempSelectOrderFeeKeys: [],
                statementFee: [],
                newArr: [],
                newArrKey: []
            }
        } else {
            this.setState({
                feeList: defaultFeeList,
                defaultFeeList: defaultFeeList,
                tempSelectOrderFeeKeys: [],
                statementFee: [],
                newArr: [],
                newArrKey: []
            })
        }
    }

    handleResetFields = () => {
        this.props.form.resetFields();
        this.props.dispatch({
            type: "settlement/refreshState",
            payload: {
                feeList: []
            }
        })
        this.setState({ tempSelectOrderFeeKeys: [], feeList: [], statementFee: [], newArr: [], newArrKey: [] })
    }


    returnFeeList = () =>{
        if(this.state.newArrKey.length != this.state.tempSelectOrderFeeKeys.length){
            message.error("您有已勾选的费用未填写结算金额!");
            return;
        }
        return this.state.newArr;
    }


    handleSearch = () => {
        let values = this.props.form.getFieldsValue();

        this.props.dispatch({
            type: 'settlement/queryStatetemntDetail',
            payload: {
                id: this.props.cstId,
                stObjId: 999999999,
                orderNo: values.orderNo,
                contractNo: values.contractNo
            }
        });
    };

    columns = [
        {title: '订单编号', dataIndex: 'orderno', key: 'orderno'},
        {title: '合同协议号', dataIndex: 'contractno', key: 'contractno'},
        {title: '费用种类', dataIndex: 'chargetype', key: 'chargetype'},
        {title: '币种', dataIndex: 'currency', key: 'currency'},
        {title: '采购成本', dataIndex: 'cost', key: 'cost'},
        {title: '结余金额', dataIndex: 'balance', key: 'balance'},
        {
            title: '本次结算金额', dataIndex: 'costAmt', key: 'costAmt',
            render: (text, record, index) => {
                return (
                    <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.costAmt} onChange={this.handleChange.bind(this, record)} />
                )
            }
        },
        {title: '本次结余金额', dataIndex: 'costBalance', key: 'costBalance'},
        {title: '备注', dataIndex: 'memo', key: 'memo'},
        {title: '创建时间', dataIndex: 'createtime', key: 'createtime'}
    ];

    amtColumns =  [
        { title: '客户编码', dataIndex: 'customerno', key: 'customerno'},
        { title: '客户名称', dataIndex: 'companyname', key: 'companyname'},
        { title: '账户总额', dataIndex: 'amount', key: 'amount'},
        { title: '可用余额', dataIndex: 'balance', key: 'balance'},
    ];


    handleChange = (record, value) => {
        let feeList = R.clone(this.state.feeList);
        let costBalance = 0;
        if(value){
            costBalance = record.balance - value;
            costBalance = costBalance.toFixed(4);
        }

        R.map((row) => {
            if (row.id === record.id) {
                if(row.balance < value){
                    message.error("本次结算金额大于结余金额！");
                    return;
                }else {
                    row.costBalance = costBalance;
                    row.costAmt = value ? value : 0;
                }
            }
        }, feeList)

        let newArr = this.state.newArr;
        let statementFee = this.state.statementFee;
        let newArrKey = this.state.newArrKey;

        if(statementFee.length > 0){
            R.map((row) => {
                if (row.id === record.id && !newArrKey.includes(record.id)) {
                    newArr.push({ costAmt: value, costId: record.id, orderId: record.orderid, costSourceAmt: record.cost, costBalance: costBalance });
                    newArrKey.push(record.id);

                }else if(row.id === record.id && newArrKey.includes(record.id)) {
                    if(value){
                        R.map((row) => {
                            if(row.costId === record.id){
                                row.costAmt= value;
                                row.costBalance= costBalance;
                            }
                        }, newArr)
                    }else{
                        newArr.splice(newArr.findIndex(item => item.costId === record.id), 1);
                        newArrKey.splice(newArrKey.findIndex(item => item === record.id), 1);
                    }
                }
            }, statementFee)
        }

        this.setState({ feeList: feeList, newArr: newArr, newArrKey: newArrKey });
    }


    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;

        let productSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ tempSelectOrderFeeKeys: selectedRowKeys, statementFee: selectedRows })

                let newArr = this.state.newArr;
                let newArrKey = this.state.newArrKey;

                if(selectedRows.length > 0){
                    if (selectedRowKeys.length > 1) {
                        selectedRows.map(value => {
                            if (!newArrKey.includes(value.id) && value.costAmt) {
                                newArr.push({
                                    costAmt: value.costAmt,
                                    costId: value.id,
                                    orderId: value.orderid,
                                    costSourceAmt: value.cost,
                                    costBalance: value.costBalance
                                });
                                newArrKey.push(value.id);
                            }
                        })
                        newArr.map(value => {
                            if (!selectedRowKeys.includes(value.costId)) {
                                newArr.splice(newArr.findIndex(item => item.costId === value.costId), 1);
                                newArrKey.splice(newArrKey.findIndex(item => item === value.costId), 1);
                            }
                        })

                    } else {
                        R.map((row) => {
                            if (!newArrKey.includes(row.id) && row.costAmt) {
                                newArr.push({ costAmt: row.costAmt, costId: row.id, orderId: row.orderid,
                                    costSourceAmt: row.cost, costBalance: row.costBalance
                                });
                                newArrKey.push(row.id);
                            }
                        }, selectedRows)

                        newArr.map(value => {
                            if (!selectedRowKeys.includes(value.costId)) {
                                newArr.splice(newArr.findIndex(item => item.costId === value.costId), 1);
                                newArrKey.splice(newArrKey.findIndex(item => item === value.costId), 1);
                            }
                        })
                    }
                }else{
                    newArr = [];
                    newArrKey = [];
                }

                this.setState({ newArr: newArr, newArrKey: newArrKey });
            },

            selectedRowKeys : this.state.tempSelectOrderFeeKeys,
        };


        let cstAmt =  this.props.forexPurchase.cstAmtList ? this.props.forexPurchase.cstAmtList : {};

        let datalist = [];
        datalist.push({ customerno: this.props.customerno,
                        companyname: this.props.companyname,
                        amount: cstAmt.amount,
                        balance: cstAmt.balance
                      });

        return (
            <div>
                <Row>
                    <Col span={8}><FormItem {...formItemLayout} label={'订单编号'}>{getFieldDecorator('orderNo')(<Input />)}</FormItem></Col>
                    <Col span={8}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractNo')(<Input />)}</FormItem></Col>
                    <Col span={7} style={{ float: 'right' }}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this)}>查询</Button>
                    </Col>
                </Row>

                <Tabs tabPosition={'top'}>
                    <TabPane tab="客户资金" key="1">
                        <div>
                            <Table rowKey="id"
                                   dataSource={datalist}
                                   columns={this.amtColumns} bordered={true}
                                   size={'middle'} scroll={{x: true}}
                                   pagination={false}/>
                        </div>
                    </TabPane>
                </Tabs>

                <Tabs tabPosition={'top'}>
                    <TabPane tab="订单费用" key="1">
                        <div>
                                <Table rowKey="id"
                                       dataSource={R.isNil(this.state.feeList) ? [] : this.state.feeList}
                                       columns={this.columns} bordered={true}
                                       size={'middle'} scroll={{x: true}}
                                       rowSelection={productSelection}
                                       pagination={false}/>
                        </div>
                    </TabPane>
                </Tabs>
            </div>

        )
    }
})


